<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

use \GatewayWorker\Lib\Gateway;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 *
 * GatewayWorker开发参见手册：
 * @link http://gatewayworker-doc.workerman.net/
 */
class Event
{
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     * @link http://gatewayworker-doc.workerman.net/gateway-worker-development/onconnect.html
     */
    public static function onConnect($client_id)
    {
        Gateway::sendToClient($client_id, json_encode([
        	'type'=>'setCid',
        	'cid'=>$client_id
        ]));
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param string $message 具体消息
    * @link http://gatewayworker-doc.workerman.net/gateway-worker-development/onmessage.html
    */
   public static function onMessage($client_id, $message)
   {
   		$message = json_decode($message,true);
   		$type = $message['type'];
		
   		$data = [];
   		switch ($type){
   			case 'newPersona':
   				$data = [
   					'type'=>'newPersona',
   					'x'=>$message['x'],
   					'y'=>$message['y'],
   					'cid'=>$client_id,
   					'name'=>$message['name'],
   					'deg'=>0
   				];
   				break;
   			case 'gotoPosition':
   				$data = [
   						'type'=>'setPosition',
   						'x'=>$message['x'],
   						'y'=>$message['y'],
   						'cid'=>$message['cid'],
   						'name'=>$message['name'],
   						'deg'=>$message['deg']
   				];
   				break;
   			case 'setContent':
   				$data = [
   						'type'=>'setContent',
   						'content'=>$message['content'],
   						'name'=>$message['name']
   				];
   				break;
   			case 'ping':
   				break;
   		}
   		
   		if(count($data)){
   			Gateway::sendToAll(json_encode($data));
   		}
   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
       GateWay::sendToAll(json_encode(['type'=>'deletePersona','cid'=>$client_id]));
   }
}
